package sz.szsmk.citizencard.ui.activity;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.chenenyu.router.Router;
import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.VerificationActivityBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.response.BaseBean;
import sz.szsmk.citizencard.model.network.bean.response.CheckThirdAppRes;
import sz.szsmk.citizencard.model.network.bean.response.IUserInfo;
import sz.szsmk.citizencard.model.network.bean.response.ImgCodeRes;
import sz.szsmk.citizencard.model.network.bean.response.RegisterResponse;
import sz.szsmk.citizencard.model.network.bean.response.ThirdAppLoginRes;
import sz.szsmk.citizencard.model.network.bean.response.UserBean;
import sz.szsmk.citizencard.mvp.contract.ICheckCodeContact;
import sz.szsmk.citizencard.mvp.presenter.CheckCodePresenter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.ui.dialogs.VerifyCodeDialog;
import sz.szsmk.citizencard.util.ACache;
import sz.szsmk.citizencard.util.AndroidUtils;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PubUtils;
import sz.szsmk.citizencard.util.TimeCount;
import sz.szsmk.citizencard.widget.VerifyCodeView;

/**
 * Copyright (c)2018
 * author: zdh
 * created on: 2018/5/31 16:50
 * description:
 */
@Route("checkCode")
public class CheckCodeActivity extends IBaseActivity<CheckCodePresenter, VerificationActivityBinding>
        implements ICheckCodeContact.ICheckCodeView, View.OnClickListener {

    private Button btn_confirm;
    private String codeNum;
    private String userPhone;
    private String type;
    private VerifyCodeView judgeCode;
    private String codeType;
    private TimeCount timeCount;
    private String androidId;
//    private String login_type;


    @Override
    protected int attachLayoutRes() {
        return R.layout.verification_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
//        dataBinding.setpsdTitle.settingTitle.setText("验证验证码");
        dataBinding.btnSure.setEnabled(false);
        dataBinding.btnSure.setBackground(getResources().getDrawable(R.drawable.shape_bg_blue_unfocus));
        dataBinding.setpsdTitle.back.setOnClickListener(this);
        dataBinding.checkBtnAgain.setOnClickListener(this);
        type = getIntent().getStringExtra("type");
        codeType = getIntent().getStringExtra("codeType");
        userPhone=getIntent().getStringExtra("userPhone");

        String userinfo = ACache.get(this).getAsString("userinfo");
        IUserInfo mUserInfo = new Gson().fromJson(userinfo, IUserInfo.class);
        if(mUserInfo!=null){
            IUserInfo.UserExBean userEx = mUserInfo.getUserEx();
            if (userEx != null) {
                userPhone = userEx.getMobile();
            }
        }

        androidId = AndroidUtils.getAndroidId(DaggerApplication.getIns());
        if (type != null) {
            if (type.equals("modifyPhone")||type.equals("resetGes")) {
                dataBinding.checkBtnAgain.setText("发送验证码");
                dataBinding.checkBtnAgain.setTextColor(getResources().getColor(R.color.color_00AAFF));
            } else {
                setTimeCount();
            }


        }
//        setTimeCount();
        setCode();
    }

    private void setCode() {
        judgeCode = dataBinding.judgeCode;
        judgeCode.setInputCompleteListener(new VerifyCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                codeNum = judgeCode.getEditContent();
                dataBinding.btnSure.setEnabled(true);
                dataBinding.btnSure.setBackground(getResources().getDrawable(R.drawable.shape_bg_blue));
//                Toast.makeText(CheckCodeActivity.this, "inputComplete: " + judgeCode.getEditContent(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void invalidContent() {

            }
        });
        dataBinding.btnSure.setOnClickListener(this);
        dataBinding.judgeUserPhone.setText(settingphone(this.userPhone));
    }

    private void setTimeCount() {
        timeCount = new TimeCount(dataBinding.checkBtnAgain, 60000, 1000);
        timeCount.start();
//        dataBinding.checkBtnAgain.setOnClickListener(this);
    }

    @Override
    protected void updateViews() {

    }

    /**
     * 设置手机号中间四位隐藏
     *
     * @param phone
     * @return
     */
    public static String settingphone(String phone) {
        if(!TextUtils.isEmpty(phone)){
            String phone_s = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
            return phone_s;
        }
        return "";
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_sure) {
            if (!TextUtils.isEmpty(codeNum)) {
                mPresenter.checkMyCode(userPhone, codeNum, codeType);
            } else {
                showToast("请输入验证码");
            }
        } else if (id == R.id.check_btn_again) {//                timeCount.start();
            mPresenter.getImgCode(userPhone);
//                setTimeCount();
//                mPresenter.getCode(codeType, androidId, userPhone);
        } else if (id == R.id.back) {
            finish();
        }
    }

    @Override
    public void registSuccess(UserBean response) {
        if (null != response) {
            String code = response.getCode();
            if (code != null) {
                if (code.equals("000000")) {
//                    ARouter.getInstance().("setpsd")
//                            .with("type", type)
//                            .with("mobile", userPhone)
//                            .with("sms_code", codeNum)
//                            .go(this);
                    //注册成功 将协议认同结果上传到服务器
                    mPresenter.addUserAppAgreementRecord(AndroidUtils.getVersionName(), "android", "zhsz_app_zhuce",response.getAccess_token());
                } else {
                    Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return;
        }
        return;

    }

    @Override
    public void regeistFile(RegisterResponse message) {

        Toast.makeText(this, message.getMessage(), Toast.LENGTH_SHORT).show();
    }

    /**
     * 用户不存在
     *
     * @param message
     */
    @Override
    public void checkUserFail(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void checkUserSucc(String userPhone) {
        if (type.equals("modifyPhone")) {
            JumpUtils.jump(this, "modifyPhone", 0);
            finish();
        } else{
            Router.build("setpsd")
                    .with("type", type)
                    .with("mobile", this.userPhone)
                    .with("sms_code", codeNum)
                    .with("sms_type",codeType)
                    .go(this);
            finish();

        }
    }

    @Override
    public void getCodeSucc() {

    }

    @Override
    public void getCodeFail() {

    }

    @Override
    public void checkMycodeSucc(String message,String sms_code,String sms_type) {
        String login_type = ACache.get(this).getAsString("login_type");
        if (Constant.is_third){
            mPresenter.checkThirdAppMobile(userPhone, login_type);
        }else {
            if (codeType.equals("2")) {
                Router.build("setpsd")
                        .with("type", type)
                        .with("mobile", userPhone)
                        .with("sms_code", sms_code)
                        .with("sms_type", sms_type)
                        .go(this);
                finish();
            } else if (codeType.equals("4")) {

                JumpUtils.jump(this, "modifyPhone", 0);
                finish();
            } else if(type.equals("resetGes")){
                Bundle bundle = new Bundle();
                bundle.putBoolean("isNeedVaild", true);
                JumpUtils.jumptoNatvie(this, "gesPasswordSettingActivity", 0,bundle);
                finish();
            }else{
                Router.build("setpsd")
                        .with("type", type)
                        .with("mobile", userPhone)
                        .with("sms_code", sms_code)
                        .with("sms_type", sms_type)
                        .go(this);
                finish();
            }
        }
    }

    @Override
    public void checkMycodeFail(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void checkThirdAppMobileSucc(CheckThirdAppRes response) {
        if (response.getCheckStatus().equals("1")) {

            mPresenter.loginThird(userPhone);
        } else {
            Router.build("setpsd")
                    .with("type", type)
                    .with("mobile", this.userPhone)
                    .with("sms_code", codeNum)
                    .go(this);
            finish();
        }
    }

    @Override
    public void checkThirdAppMobileFail(CheckThirdAppRes response) {
//        PubUtils.popTipOrWarn(CheckCodeActivity.this, response.getMessage());
//        finish();
    }

    @Override
    public void loginThirdSucc() {
        Router.build("main")
                .go(this);
        finish();
    }

    @Override
    public void loginThirdFail(ThirdAppLoginRes response) {
        PubUtils.popTipOrWarn(CheckCodeActivity.this, response.getMessage());
        finish();
    }

    @Override
    public void addUserAppAgreementRecordSucc(BaseBean baseBean) {
        //隐式的数据处理 无需进行界面反馈

    }

    @Override
    public void addUserAppAgreementRecordFail() {
//隐式的数据处理 无需进行界面反馈
    }

    @Override
    public void getSmsCodeSucc() {

        if(verifyCodeDialog.isShowing()){
            verifyCodeDialog.dismiss();
        }
        setTimeCount();
    }

    @Override
    public void getSmsCodeFail(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
   VerifyCodeDialog verifyCodeDialog;
    @Override
    public void getImgCodeSucc(ImgCodeRes imgCodeRes) {
        if (verifyCodeDialog!=null&&verifyCodeDialog.isShowing()) {
            verifyCodeDialog.update(Constant.BASE_URL + imgCodeRes.getImgUrl());
        } else {
            verifyCodeDialog = new VerifyCodeDialog(this, userPhone, Constant.BASE_URL + imgCodeRes.getImgUrl());
            verifyCodeDialog.show();
            verifyCodeDialog.setCancelable(false);
            verifyCodeDialog.setIVerifyCodeDialogNew(new VerifyCodeDialog.IVerifyCodeDialog() {
                @Override
                public void onclick(@NotNull String phone, @NotNull String code) {
                    //验证验证码请求发出 在获取短信里面去验证验证码
                    mPresenter.getCode(code,codeType,androidId, userPhone);
                }

                @Override
                public void refresh(@NotNull String phone) {
                    //刷新验证码
                    mPresenter.getImgCode(userPhone);
                }
            });
        }
    }

    @Override
    public void getImgCodeFail() {
        Toast.makeText(CheckCodeActivity.this, "获取图片验证码失败，请稍后重新获取", Toast.LENGTH_SHORT).show();
    }
}
